import React, {Component} from 'react';

import {
    StyleSheet,
    Text,
    View,
    Platform,
    FlatList,
    Dimensions,
    TouchableOpacity,
    Image,
    ActivityIndicator,
    TextInput,
} from 'react-native';

import HttpUtils from '../../utils/HttpUtils';
import HttpUrls from '../../utils/HttpUrls';
import Constant from '../../utils/Constant'; //全局变量
import Header from '../../components/header';
import Loading from '../../utils/Loading';
import NoData from '../../utils/NoData';
import {getImgUrl} from '../../utils/ComFunction';
import moment from 'moment';
import RegionPickerView from '../../components/Tool/RegionPickerView';
import BuyerDetailPage from './BuyerDetailPage';
import CommonConfirmPop from "../../components/dialog/CommonConfirmPop";

const isIos = Platform.OS == 'ios';
const screenW = Dimensions.get('window').width;
const screenH = Dimensions.get('window').height;

let navigation;

export default class BuyerListPage extends Component {
    constructor(props) {
        super(props);
        this.state = {
            searchKey: '', //搜索关键字

            buyerLists: [],
            rescissionShow: false,

            filterShowList: [],

            isRefresh: false,
            showFoot: 0, // 控制foot， 0：隐藏footer  1：已加载完成,没有更多数据   2 ：显示加载中
            pageNo: 1,

            tagReceivingCityId: null, // 城市 id
            merchantId: null, // 门店id

            showCityPicker: false, // 城市弹出
            cityTitle: '城市', // 城市名称
            merchantTitle: '门店', // 门店名称

            isBuyer: true, // 是否完善了标签
            dialogVisible: false, // 提示用户完善标签
        };
    }

    render() {
        navigation = this.props.navigation;
        return (
            <View style={styles.container}>
                <Header navigation={navigation} Title={'买手列表'} />

                {/* 搜索框 */}
                <View style={styles.searchContainer}>
                    <View style={styles.searchLayout}>
                        <Image
                            source={require('source/image/electron/search.png')}
                            style={styles.sarchIcon}
                        />
                        <TextInput
                            editable={true}
                            style={styles.inputbox}
                            placeholder="请输入买手姓名"
                            placeholderTextColor={'#999999'}
                            maxLength={17}
                            value={this.state.searchKey}
                            onChangeText={this.onChangeTextHandle}
                            onEndEditing={this.handleKeyboardFinish.bind(this)}
                        />
                    </View>
                </View>

                {/* 城市选择 */}
                <View style={styles.chooseContainer}>
                    <TouchableOpacity
                        style={styles.choosePer}
                        onPress={() => {
                            this.setState({
                                showCityPicker: true,
                            });
                        }}>
                        <Text style={styles.choosetype}>城市</Text>
                        <Image
                            style={styles.filterImg}
                            source={require('source/image/comm/down_small_gray.png')}
                        />

                    </TouchableOpacity>

                    {/* 门店选择 */}
                    <TouchableOpacity
                        style={styles.choosePer}
                        activeOpacity={0.8}
                        onPress={() => {
                            navigation.navigate('SelectStorePage', {
                                onGoBack: (selectedMerchantId, selectedMerchantName) => {
                                    // console.log('Selected Merchant ID:', selectedMerchantId);
                                    // console.log('Selected Merchant selectedMerchantName:', selectedMerchantName);

                                    let seriesObj = {
                                        title: selectedMerchantName,
                                        key: 'merchant',
                                        value: selectedMerchantId,
                                    }
                                    this.addRenderFilter(seriesObj)

                                    // 接收到门店ID后更新状态并刷新列表
                                    this.setState({
                                        merchantId: selectedMerchantId,
                                        merchantTitle: selectedMerchantName, // 获取名称
                                    }, () => {
                                        this.refreshData(); // 刷新买手列表
                                    });
                                }
                            });
                        }}>
                        <View style={styles.choosePerinner}>
                            <Text style={styles.choosetype}  numberOfLines={1} ellipsizeMode="tail" >门店</Text>
                            <Image
                                source={require('source/image/electron/choosearrow.png')}
                                style={styles.choosearrow}
                            />
                        </View>
                    </TouchableOpacity>

                </View>

                {/* 条件清除 */}
                {this.renderFilterShow()}

                {/* 列表数据 */}
                {this.renderList()}

                <RegionPickerView
                    show={this.state.showCityPicker}
                    mode={'pc'}
                    hide={() => {
                        this.setState({
                            showCityPicker: false,
                        });
                    }}
                    selectArea={item => {
                        // let address = item.provinceName + item.cityName;
                        let address = item.cityName;
                        let addressObj = {
                            cityId: item.cityId,
                            title: address,
                            key: 'address',
                            value: address,
                        };
                        this.addFilter(addressObj);

                        this.setState(
                            {
                                showCityPicker: false,
                                carProvince: item.provinceId,
                                carCity: item.cityId,
                            },
                            function () {
                                this.refreshData();
                            },
                        );
                    }}
                />


                {this.state.dialogVisible ?
                    <CommonConfirmPop
                        visible={this.state.dialogVisible}
                        content={'未选择买手标签, 是否去完善'}
                        onClose={() => {
                            this.setState({
                                dialogVisible: false
                            })
                        }}
                        onSure={() => {
                            this.setState({
                                dialogVisible: false
                            })
                            navigation.navigate('BuyerSetLabelPage', { })
                        }}
                        sureText={'去完善'}
                        cancelText={'关闭'}
                    >

                    </CommonConfirmPop>
                    :
                    null
                }

                <Loading onRef={ref => (this.Loading = ref)} />
            </View>
        );
    }

    // 选择城市触发
    addFilter(addressObj){
        let seriesObj = {
            title: addressObj.title,
            key: 'city',
            value: addressObj.cityId,
        }
        this.addRenderFilter(seriesObj)

        this.setState( {
            tagReceivingCityId: addressObj.cityId,
            cityTitle: addressObj.title,

        }, function () {
            // this.refreshData();
        })
    };

    componentDidMount() {
        // this.checkUserIsBuyer();
        // console.log('BuyerListPage')
        this.refreshData();
    }

    //关键字输入信息变化
    onChangeTextHandle = value => {
        this.setState({searchKey: value});
    };

    //清除搜索关键词
    clearSearch() {
        this.setState(
            {
                searchKey: '',
            },
            function () {
                this.refreshData();
            },
        );
    }

    //关键字搜索完成输入直接搜索
    handleKeyboardFinish() {
        this.refreshData();
    }

    renderList() {
        return (
            <View
                style={{
                    flex: 1,
                    marginBottom: Constant.isIPhoneX ? Constant.bottomHeight + 0 : 0,
                }}>
                <FlatList
                    data={this.state.buyerLists}
                    renderItem={this.renderItemView.bind(this)}
                    extraData={this.state}
                    onRefresh={this.refreshData}
                    refreshing={this.state.isRefresh}
                    ListEmptyComponent={this.renderEmpty.bind(this)}
                    ListFooterComponent={this.renderFooter.bind(this)}
                    onEndReached={this._onEndReached.bind(this)}
                    onEndReachedThreshold={0.3}
                />
            </View>
        );
    }

    renderItemView({item, index}) {
        return (
            <TouchableOpacity
                activeOpacity={0.8}
                key={item.contractNo}
                onPress={() => {
                    // navigation.navigate('BuyerSetLabelPage');
                    navigation.navigate('BuyerInfoPage', {
                      buyerId: item.buyerId,
                    });
                }}>
                {/* 列表数据 */}
                <View style={styles.itemcontainer}>
                    {/* 买手相关 */}
                    <View style={styles.contractCarContainer}>
                        {item.avatar ? (
                            <Image
                                style={styles.contractcar}
                                source={{
                                    uri: getImgUrl(item.avatar),
                                }}
                            />
                        ) : (
                            <Image
                                source={require('source/image/seekCenter/default_avatar.png')}
                                style={styles.contractcar}
                            />
                        )}
                    </View>

                    <View style={styles.buyerInfoList}>
                        <Text style={styles.buyerInfo}>
                            <Text style={{color: '#333', fontSize: 14}}>{item.fullname ? item.fullname : ''}</Text>
                            <Text> </Text>
                            <Text style={{color: '#FFA500', fontSize: 13}}>
                                @{item.merchantAbbreviation ? item.merchantAbbreviation : '暂无'}
                            </Text>
                        </Text>
                        <View style={styles.buyerInfoDesc}>
                            <Text
                                numberOfLines={2}
                                ellipsizeMode="tail"
                                style={{fontSize: 14, color: '#666'}}>
                                简介: {item.preferences ? item.preferences : '暂无信息'}
                            </Text>
                        </View>
                        <View style={styles.buyerInfoTage}>
                            {/* 遍历 item.buyerTags */}
                            {item.limitShowBuyerTags?.map((tag, index) => {
                                if(tag.tagValueText == '不限'){
                                    return null;
                                }
                                return (
                                    <View style={styles.tagItem} key={index}>
                                        <Text style={styles.tagText}>
                                            {tag.tagValueText  ? tag.tagValueText : ''}
                                        </Text>
                                    </View>
                                );
                            })}
                        </View>
                    </View>
                </View>
                <View style={styles.sepLine} />
            </TouchableOpacity>
        );
    }

    // 条件清除
    renderFilterShow() {
        return (
            <View style={styles.filterShowContain}>
                {this.state.filterShowList.map((item, index) => {
                    if (item.key == 'clear') {
                        return (
                            <TouchableOpacity
                                key={index}
                                style={styles.filterShowItem}
                                onPress={() => {
                                    this.clearFilterShow()
                                }}>
                                <Image style={styles.filterShowClearImg} source={require('source/image/comm/btn_clear_history.png')}></Image>
                                <Text style={styles.filterShowText}>清空</Text>

                            </TouchableOpacity>
                        )
                    } else {
                        return (
                            <TouchableOpacity
                                key={index}
                                style={styles.filterShowItem}
                                onPress={() => {
                                    this.removeFilterShow(item, index)
                                }}>
                                <Text style={styles.filterShowText}>{item.title}</Text>
                                <Image style={styles.filterShowCloseImg} source={require('source/image/comm/icon_close.png')}></Image>
                            </TouchableOpacity>
                        )
                    }

                })
                }
            </View>
        )
    }

    addRenderFilter(filterModel) {
        let filterShowList = this.state.filterShowList
        let clear = {
            key: 'clear',
        }
        if (filterShowList.length == 0) {
            filterShowList.push(filterModel)
            filterShowList.push(clear)
        } else {
            let isExist = false
            for (let i = 0; i < filterShowList.length; i++) {
                if (filterShowList[i].key == filterModel.key) {
                    isExist = true
                    filterShowList[i] = filterModel
                }
            }
            if (!isExist) {
                filterShowList.splice(filterShowList.length - 2, 0, filterModel);
            }
        }

        this.setState({
            filterShowList: filterShowList
        })
    }

    // 条件清除
    clearFilterShow() {
        this.setState({
            filterShowList: [],
            tagReceivingCityId: null,
            merchantId: null
        }, function () {
            this.refreshData()
        })
    }

    // 删除条件
    removeFilterShow(item, index) {
        let filterShowList = this.state.filterShowList
        let temp = []
        for (let i = 0; i < filterShowList.length; i++) {
            if (i != index) {
                temp.push(filterShowList[i])
            }
        }

        if (item.key == 'city') {
            this.setState({
                tagReceivingCityId: null
            })
        }
        if(item.key == 'merchant'){
            this.setState({
                merchantId: null
            })
        }

        if(temp.length == 1){
            temp = []
        }

        this.setState({
            filterShowList: temp
        }, function () {
            this.refreshData()
        })
    }

    renderEmpty() {
        return <NoData Desc="暂无数据" style={{marginTop: gREM(200)}} />;
    }

    //刷新数据
    refreshData = () => {
        this.setState(
            {
                isRefresh: true,
                pageNo: 1,
                buyerLists: [],
            },
            function () {
                this.getBuyerList();
            },
        );
    };

    renderFooter() {
        if (this.state.showFoot === 1) {
            return null;
        } else if (this.state.showFoot === 2) {
            return (
                <View style={styles.footer}>
                    <ActivityIndicator size="small" color="#999999" />
                    <Text style={styles.loadMoreTextStyle}>正在加载更多数据...</Text>
                </View>
            );
        } else if (this.state.showFoot === 0) {
            return null;
        }
    }

    _onEndReached() {
        //如果是正在加载中或没有更多数据了，则返回
        if (this.state.showFoot !== 0) {
            return null;
        }
        //底部显示正在加载更多数据
        this.setState(
            {
                showFoot: 2,
                pageNo: this.state.pageNo + 1,
            },
            function () {
                this.getBuyerList();
            },
        );
    }

    // 买手列表获取
    getBuyerList() {
        let param = {
            pageNo: this.state.pageNo,
            pageSize: 20,
            tagReceivingCityId: this.state.tagReceivingCityId,
            merchantId: this.state.merchantId,
            fullname: this.state.searchKey,
        };

        HttpUtils.postRequest(HttpUrls.queryBuyerList, param)
            .then(result => {
                let data = result.data;
                if (data) {
                    let resultList = data.resultList;
                    if (resultList && resultList.length > 0) {
                        this.setState({
                            buyerLists: this.state.buyerLists.concat(resultList),
                            isRefresh: false,
                            showFoot: 1,
                        });
                        setTimeout(() => {
                            this.setState({
                                showFoot: resultList.length >= 20 ? 0 : 1,
                            });
                        }, 200);
                    } else {
                        this.setState({
                            showFoot: 1,
                            isRefresh: false,
                        });
                    }
                } else {
                    this.setState({
                        showFoot: 1,
                        isRefresh: false,
                    });
                }
            })
            .catch(error => {});
    }

    // 检查买手是否已经完善标签
    checkUserIsBuyer = () => {
        HttpUtils.getRequest(HttpUrls.checkHaveTage)
            .then(result => {
                // console.log('checkUserIsBuyer', result);
                if (result && result.code == 0) {
                    // 请求成功
                    const isBuyer = result.data; // 假设返回的数据结构中有 isBuyer 字段
                    // 可以根据 isBuyer 的值做进一步处理，比如跳转或提示
                    if (!isBuyer) {
                        this.setState({ isBuyer: false, dialogVisible: true });
                        console.log("用户未完善标签");
                    }
                } else {
                    console.error("请求失败:", result.message);
                }
            })
            .catch(error => {
                console.error("请求错误:", error);
            });
    };
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#F9F9F9',
    },

    searchContainer: {
        paddingTop: 10,
        // height: 40,
        backgroundColor: '#ffffff',
        flexDirection: 'row',
        alignItems: 'center',
    },

    searchLayout: {
        width: screenW - 30,
        height: 34,
        backgroundColor: '#F7F8F8',
        borderRadius: 5,
        flexDirection: 'row',
        alignItems: 'center',
        marginLeft: 15,
    },

    sarchIcon: {
        width: 16,
        height: 16,
        marginLeft: 10,
        marginRight: 10,
    },

    inputbox: {
        width: screenW - 40 - 30,
        height: 34,
        fontSize: 14,
        padding: 0,
        margin: 0,
    },
    sarchClose: {
        width: 15,
        height: 15,
    },

    chooseContainer: {
        height: 44,
        backgroundColor: '#ffffff',
        flexDirection: 'row',
    },

    choosePer: {
        width: '50%',
        height: 45,
        alignItems: 'center',
        justifyContent: 'center',
        flexDirection: 'row',
    },

    choosePerinner: {
        alignItems: 'center',
        justifyContent: 'center',
        flexDirection: 'row',
        paddingHorizontal: 15,
    },

    choosetype: {
        fontWeight: '400',
        fontSize: 14,
        color: '#333333',
    },

    choosearrow: {
        width: 15,
        height: 15,
    },

    itemcontainer: {
        backgroundColor: '#ffffff',
        flexDirection: 'row',
        paddingHorizontal: 15,
        paddingVertical: 15,
    },

    contractCarContainer: {
        borderRadius: 8,
        flexDirection: 'row',
    },

    contractcar: {
        width: 87,
        height: 121,
        borderRadius: 6,
        // marginRight: 15
    },

    footer: {
        flexDirection: 'row',
        height: 40,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#f6f6f6',
    },
    loadMoreTextStyle: {
        fontSize: 14,
        color: '#999999',
        marginStart: 10,
    },

    borderBottom: {
        borderBottomColor: '#E4E4E4',
        borderBottomWidth: 0.5,
        position: 'absolute',
        bottom: 0,
        width: screenW,
        marginLeft: 15,
    },

    buyerInfoList: {
        marginHorizontal: 12,
        width: '67%',
        // backgroundColor: '#c5c5c5',
        overflow: 'hidden'
    },
    buyerInfo: {
        flexDirection: 'row',
    },
    buyerInfoDesc: {
        marginTop: 5,
    },
    buyerInfoTage: {
        flexWrap: 'wrap',
        flexDirection: 'row',
        marginTop: 10,
    },
    tagItem: {
        backgroundColor: '#fff399', // 背景色
        borderRadius: 4, // 圆角
        paddingVertical: 2,
        paddingHorizontal: 6,
        marginRight: 8, // 标签之间的间距
        marginTop: 5,
    },
    tagText: {
        fontSize: 11, // 字体大小
        color: '#333333', // 文字颜色
    },

    // 选项关闭按钮
    filterClose: {
        width: 11,
        height: 11,
        marginLeft: 5
    },

    sepLine: {
        position: 'absolute',
        bottom: 0,
        left: 15,
        width: screenW - 15,
        height: 0.5,
        backgroundColor: '#e4e4e4',
    },

    // 筛选条件清除
    filterShowContain: {
        flexDirection: 'row',
        flexWrap: 'wrap',
        backgroundColor: '#fff',
        paddingHorizontal: 15
    },
    filterShowItem: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',
        // height: 30,
        backgroundColor: '#f6f6f6',
        borderRadius: 4,
        paddingHorizontal: 5,
        paddingVertical: 5,
        marginRight: 10,
        marginBottom: 5
    },
    filterShowText: {
        fontSize: 10,
        color: '#696969'
    },
    filterShowCloseImg: {
        width: 10,
        height: 10,
        marginLeft: 2
    },
    filterShowClearImg: {
        width: 12,
        height: 12,
        marginRight: 2,
        resizeMode: 'contain'
    },
});
